package com.compty.paint.web.member;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.math.RandomUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.compty.core.framework.util.FileUtil;
import com.compty.core.framework.util.HttpUtil;
import com.compty.core.framework.util.StringUtil;
import com.compty.core.struts2.BaseAction;
import com.compty.core.utils.CommonsUtil;
import com.compty.paint.domain.Advertisement;
import com.compty.paint.domain.AuditState;
import com.compty.paint.domain.CatalogType;
import com.compty.paint.domain.ImageInfo;
import com.compty.paint.domain.Painter;
import com.compty.paint.domain.SpecialSubject;
import com.compty.paint.manager.AdvertisementManager;
import com.compty.paint.manager.AuditStateManager;
import com.compty.paint.manager.CatalogTypeManager;
import com.compty.paint.manager.ImageInfoManager;
import com.compty.paint.manager.PainterManager;
import com.compty.paint.manager.SpecialSubjectManager;
import com.compty.paint.util.Constants;
import com.compty.security.domain.User;

/**
 * 特殊(专题)广告action
 */
public class SpecialSubjectAction extends BaseAction<SpecialSubject> {

	private static final long serialVersionUID = -8873917521956882861L;
	private static final String SpecialSubjectFlag = "specialsubject";
	private static final String AdvertiseFlag = "advertise";
	
	private SpecialSubjectManager specialSubjectManager;
	private PainterManager painterManager;
	private CatalogTypeManager catalogTypeManager;
	private AuditStateManager auditStateManager;
	private ImageInfoManager imageInfoManager;
	private AdvertisementManager advertisementManager;
	
	// ====================================================
	private SpecialSubject specialSubject;
	private Date startDate;
	private Date endDate;
	private String operateStr; // 1表示隐藏,2表示删除
	
    private File myFile;//上传文件
    private String fileName;//文件原始文件名
	
	/**
	 *@Todo:添加specialSubject prepare
	 *@CreateTime:2011-9-16 下午03:51:41
	 * @return
	 */
	public String addPrepare(){
		
		this.specialSubject = null;
		
		return "addPrepare";
	}
	
	/**
	 *专题预览(未保存)
	 */
	public String preview(){
		
		if( specialSubject != null){
			
			Integer  id = specialSubject.getId();
			if(id != null){
				specialSubject = specialSubjectManager.get(id);
			}
			
			Long  painterID = specialSubject.getPainterID();
			Painter  painter = painterManager.get(painterID);
			request.setAttribute("painter", painter);
			
			String back_image  = request.getParameter("back_image");
			request.setAttribute("back_image", back_image);
			
			return "preview";
		}
		
		return null;
	}
	
	/**
	 *专题预览(已保存过)
	 */
	public String preview_update(){
		
		if( specialSubject != null){
			
			Long  painterID = specialSubject.getPainterID();
			Painter  painter = painterManager.get(painterID);
			request.setAttribute("painter", painter);
			
			String back_image  = request.getParameter("back_image");
			if( back_image!= null && !"".equals(back_image)){
				request.setAttribute("back_image", back_image);
			}else{
				Integer  id = specialSubject.getId();
				if( id != null){
					SpecialSubject special = specialSubjectManager.get(id);
					if( special != null){
						if(special.getImageInfo() != null){
							special.getImageInfo().getId();
							special.getImageInfo().getSuffix();
							specialSubject.setImageInfo(special.getImageInfo());
						}
					}
				}
			}
			
			return "preview";
		}
		
		return null;
	}
	
	/**
	 * 查看专题
	 */
	public String view(){
		
		String idStr = request.getParameter("id");
		Integer id = Integer.valueOf(idStr);
		
		this.specialSubject = specialSubjectManager.get(id);
		
		if( specialSubject != null){
			return "view";
		}
		
		return null;
	}
	
	/**
	 *查找画家(专题绑定画家)
	 */
	public String queryPainters(){
		
		String painter_name = request.getParameter("painter_name")== null?"":request.getParameter("painter_name");
		String catalog_type = request.getParameter("catalog_type")== null?"":request.getParameter("catalog_type");
		
		this.page = painterManager.queryPaintersByNameAndCatalogtype(curPage,20,painter_name,catalog_type);
		
		request.setAttribute("painter_name", painter_name);
		request.setAttribute("catalog_type", catalog_type);
		
		List<CatalogType>  catalogTypeList = catalogTypeManager.getAll();
		request.setAttribute("catalogTypeList", catalogTypeList);
		
		return "query_painter";
	}
	
	/**
	 *@Todo:分页列出专题广告条
	 *@CreateTime:2011-9-16 上午09:33:11
	 * @return
	 */
	public String list(){
		
	   Criteria criteria;
		  
        if (sort != null) {
            boolean isAsc = dir.equalsIgnoreCase("asc");
            criteria = specialSubjectManager.createCriteria(sort, isAsc);
        } else {
            criteria = specialSubjectManager.createCriteria();
        }
        criteria.addOrder(Order.desc("id"));
        
        User userInfo = (User) session.getAttribute(Constants.Userinfo);
        if(userInfo!= null && "0".equals(userInfo.getAdministratorFlag())){
        	  criteria = criteria.add(Restrictions.eq("entryPerson", userInfo));
        }
        
        if(startDate != null){
        	 criteria = criteria.add(Restrictions.ge("uploadTime", startDate));
        }
        
        if(endDate != null){
        	 criteria = criteria.add(Restrictions.lt("uploadTime", endDate));
        }

        if ((filterTxt != null) && (filterValue != null)&& (!filterTxt.equals("")) && (!filterValue.equals(""))) {
            criteria = criteria.add(Restrictions.like(filterTxt,
                        "%" + filterValue + "%"));
        }

        this.page = specialSubjectManager.pagedQuery(criteria, curPage, pageSize);
        
        return "list";
	}
	
	/**
	 *@Todo:保存specialSubject
	 *@CreateTime:2011-9-16 上午09:44:34
	 * @return
	 */
	public String save(){
		
		if(specialSubject != null){
			
			User userInfo = (User) session.getAttribute(Constants.Userinfo);
			specialSubject.setEntryPerson(userInfo);
			specialSubject.setModifyPerson(userInfo);
			
			specialSubject.setUploadTime(Calendar.getInstance().getTime());
			specialSubject.setModifyTime(Calendar.getInstance().getTime());
			
			if(Constants.Auto_Audit){
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Pass);
				specialSubject.setAuditState(auditState);
			}else{
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Init);
				specialSubject.setAuditState(auditState);
			}
			
			String picImage = request.getParameter("back_image");
			if( picImage!= null && !"".equals(picImage)){
				String imageFilePath = getImageUploadPath()+CommonsUtil.getPathSymbol() + picImage; //图片物理路径
				File file = new File(imageFilePath);
				ImageInfo imageInfo = saveImageToDB(file, picImage, "15",picImage,SpecialSubjectFlag);
				specialSubject.setImageInfo(imageInfo);
			}
			
			specialSubjectManager.save(specialSubject);
			
			String channelIDs = specialSubject.getChannelIDs();
			if( channelIDs != null){
				String[] arrays = channelIDs.split(",");
				for (int i = 0; i < arrays.length; i++) {
					Advertisement advertisement = buildAdvertisement(specialSubject, arrays[i]);
					advertisementManager.save(advertisement);
				}
			}
		}
		
		return "saved";
	}
	
	/**
	 *@Todo:修改specialSubject，显示详情
	 *@CreateTime:2011-9-16 上午09:45:12
	 * @return
	 */
	public String modifyPrepare(){
		
		if( specialSubject != null){
			
			Integer id = specialSubject.getId();
			this.specialSubject = specialSubjectManager.get(id);
			Long  painterID = specialSubject.getPainterID();
			Painter  painter = painterManager.get(painterID);
			request.setAttribute("painter", painter);
		}
		
		return "modifyPreare";
	}
	
	/**
	 *@Todo:修改specialSubject
	 *@CreateTime:2011-9-16 上午09:49:33
	 * @return
	 */
	public String modify(){
		
		if(specialSubject != null){
			
			SpecialSubject ad = specialSubjectManager.get(specialSubject.getId());
			
			ImageInfo imageInfo2 = ad.getImageInfo();
			Long removeId = imageInfo2 == null ? null : imageInfo2.getId();
			
			User userInfo = (User) session.getAttribute(Constants.Userinfo);
			ad.setModifyPerson(userInfo);
			
			ad.setModifyTime(Calendar.getInstance().getTime());
			ad.setBackground_color(specialSubject.getBackground_color());
			ad.setDescription1(specialSubject.getDescription1());
			ad.setDescription2(specialSubject.getDescription2());
			ad.setDescription3(specialSubject.getDescription3());
			ad.setDescription_color(specialSubject.getDescription_color());
			ad.setPainterID(specialSubject.getPainterID());
			ad.setTitle1(specialSubject.getTitle1());
			ad.setTitle1_color(specialSubject.getTitle1_color());
			ad.setTitle2(specialSubject.getTitle2());
			ad.setTitle2_color(specialSubject.getTitle2_color());
			
			String picImage = request.getParameter("back_image");
			if( picImage!= null && !"".equals(picImage)){
				String imageFilePath = getImageUploadPath() +CommonsUtil.getPathSymbol() + picImage; //图片物理路径
				File file = new File(imageFilePath);
				ImageInfo imageInfo = saveImageToDB(file, fileName, "15",picImage,SpecialSubjectFlag);
				ad.setImageInfo(imageInfo);
			}
			
			specialSubjectManager.save(ad);  //保存修改后的广告
			
			if( ad.getImageInfo() != null && removeId != null && !removeId.equals(ad.getImageInfo().getId())){//删除原来的专题图片
				imageInfoManager.deleteById(removeId);
			}
		}
		
		return "modified";
	}
	
	/**
	 *@Todo:修改specialSubject状态
	 *@CreateTime:2011-6-9 上午10:19:17
	 */
	public String changeUploadState() {

		if (specialSubject != null) {
			Integer id = specialSubject.getId();
			this.specialSubject = specialSubjectManager.get(id);

			if ("1".equals(operateStr)) {//隐藏
				specialSubject.setModifyTime(Calendar.getInstance().getTime());
				specialSubjectManager.save(specialSubject);
			} else if ("2".equals(operateStr)) { //删除
				specialSubjectManager.removeById(id);
			}
			else if("3".equals(operateStr)){
				AuditState auditState = auditStateManager.findUniqueBy("english_name", Constants.Audit_State_Pass);  //审核通过
				specialSubject.setAuditState(auditState);
				specialSubject.setModifyTime(Calendar.getInstance().getTime());
				specialSubjectManager.save(specialSubject);
			}
			else if("4".equals(operateStr)){
				AuditState auditState = auditStateManager.findUniqueBy("english_name", Constants.Audit_State_Overrule);  //审核驳回
				specialSubject.setAuditState(auditState);
				specialSubject.setModifyTime(Calendar.getInstance().getTime());
				specialSubjectManager.save(specialSubject);
			}
			else if("5".equals(operateStr)){//显示
				specialSubject.setModifyTime(Calendar.getInstance().getTime());
				specialSubjectManager.save(specialSubject);
			}
		}
		
		return "changeState";
	}
	
	/**
	 * 上传图片 
	 */
	public String uploadImage(){
		
		if ( myFile != null ) {
			
			long filenameExclude = RandomUtils.nextInt();
			String newImageFileName = filenameExclude + "."+ StringUtil.getExt(fileName) ;
			String srcpath = getImageUploadPath()+ CommonsUtil.getPathSymbol() + newImageFileName;
			File imageFile = new File(srcpath);
			FileUtil.copy(myFile, imageFile);
			
			request.setAttribute("ajaxData", "{code:\"0000\",message:\""+newImageFileName+"\"}");
			return "uploadSuccess";
		}
		
		request.setAttribute("ajaxData", "{code:\"0001\",message:\"文件上传失败。\"}");
		return "uploadSuccess";
	}
	
	/**
	 *@Todo:保存图片至DB
	 * @param file 图片文件
	 * @param originalName  图片原始名字
	 * @param sharpId 图片形状类型 15表示专题背景图片
	 */
	public ImageInfo saveImageToDB(File file,String originalName,String sharpId,String newNameUploaded,String memo){
		ImageInfo imageInfo = buildImage(file,originalName,sharpId,newNameUploaded,memo);
    	imageInfoManager.save(imageInfo);
    	writeImg(imageInfo,AdvertiseFlag);
    	return imageInfo;
	}
	
	
	public Advertisement buildAdvertisement(SpecialSubject specialSubject,String channelID){
		Advertisement advertisement = new Advertisement();
		if( specialSubject != null){
			advertisement.setAuditState(specialSubject.getAuditState());
			advertisement.setChannelID(channelID);
			advertisement.setEntryPerson(specialSubject.getEntryPerson());
			advertisement.setModifyPerson(specialSubject.getModifyPerson());
			advertisement.setModifyTime(specialSubject.getModifyTime());
			advertisement.setUploadTime(specialSubject.getUploadTime());
			advertisement.setSpecialSubjectID(specialSubject.getId());
			advertisement.setTitle(specialSubject.getTitle1());
			advertisement.setLinkAddress(HttpUtil.getFullContext(request)+"/"+specialSubject.getPainterName());
		}
		return advertisement;
	}

	public void setSpecialSubjectManager(SpecialSubjectManager specialSubjectManager) {
		this.specialSubjectManager = specialSubjectManager;
	}

	public void setAuditStateManager(AuditStateManager auditStateManager) {
		this.auditStateManager = auditStateManager;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public void setImageInfoManager(ImageInfoManager imageInfoManager) {
		this.imageInfoManager = imageInfoManager;
	}

	public String getOperateStr() {
		return operateStr;
	}

	public void setOperateStr(String operateStr) {
		this.operateStr = operateStr;
	}

	public SpecialSubject getSpecialSubject() {
		return specialSubject;
	}

	public void setSpecialSubject(SpecialSubject specialSubject) {
		this.specialSubject = specialSubject;
	}

	public void setPainterManager(PainterManager painterManager) {
		this.painterManager = painterManager;
	}

	public void setCatalogTypeManager(CatalogTypeManager catalogTypeManager) {
		this.catalogTypeManager = catalogTypeManager;
	}

	public File getMyFile() {
		return myFile;
	}

	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	public String getFileName() {
		return fileName;
	}

    public void setMyFileFileName(String fileName)  {
        this.fileName = fileName;
    }

	public void setAdvertisementManager(AdvertisementManager advertisementManager) {
		this.advertisementManager = advertisementManager;
	}
}
